<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\mill\model;

use think\Model;
use app\mill\model\Archives as ArchivesModel;
use app\mill\model\Finance as FinanceModel;
use app\admin\model\Config as ConfigModel;
use think\Db;

/**
 * 产品流水模型
 */
class Give extends Model
{
    // 设置当前模型对应的完整数据表名称
    protected $name = 'mill_order_archives_give';

    // 自动写入时间戳
    protected $autoWriteTimestamp = true;

    // 条形码每页显示数
    public static $_listRows = 500;

    //生产状态
    public static $give_status = [
        -1 =>      '开料报废',
        -2 =>      '折弯报废',
        -3 =>      '焊接报废',
        -4 =>      '组装报废',
        -5 =>      '打磨报废',
        -6 =>      '喷涂报废',
        -7 =>      '复合报废',
        -8 =>      '发货报废',
        0 =>      '待生产',
        1 =>      '开料',
        2 =>      '折弯',
        3 =>      '焊接',
        4 =>      '组装',
        5 =>      '打磨',
        6 =>      '喷涂',
        7 =>      '复合',
        8 =>      '发货',
    ];

    //生产状态
    public static $give_status_search = [
        0 =>      '待生产',
        1 =>      '开料',
        2 =>      '折弯',
        3 =>      '焊接',
        4 =>      '组装',
        5 =>      '打磨',
        6 =>      '喷涂',
        7 =>      '复合',
        8 =>      '发货',
    ];

    //生产质检状态
    public static $quality_status = [
        -1 =>     '不合格',
        -2 =>     '报废',
        -3 =>     '已取消',
        0 =>      '待质检',
        1 =>      '合格',
        2 =>      '已返修',
    ];

    //打印状态
    public static $quality_repair = [
        0 =>      '待打印',
        1 =>      '待补件',
        2 =>      '已打印',
    ];

    //各部门权限
    //process:是否需要组装
    public static $role = [
        4   =>    ['quality'=>[true]],//质检部
        5   =>    ['status'=>[1]],//开料部
        11  =>    ['status'=>[2,1]],//折弯部
        13  =>    ['status'=>[3,2,1]],//焊接部
        10  =>    ['status'=>[4,3,2,1]],//组装部
        6   =>    ['status'=>[5,4,3,2,1]],//打磨部
        7   =>    ['status'=>[6,5,4,3,2,1],'color'=>[true]],//喷涂部
        12  =>    ['status'=>[7,6,5,4,3,2,1]],//复合部
        8   =>    ['status'=>[8,7,6,5,4,3,2,1]],//发货部
        9   =>    ['status'=>[8,7,6,5,4,3,2,1]],//补扫部
    ];

    //责任部门
    public static $quality_group = [
        1    =>    5,//开料部
        2    =>    11,//折弯部
        3    =>    13,//焊接部
        4    =>    10,//组装部
        5    =>    6,//打磨部
        6    =>    7,//喷涂部
        7    =>    12,//复合部
        8    =>    8,//发货部
    ];

    //各车间不需要的流水线配置
    public static $role_mill = [
        0   =>    [6],//复合
        1   =>    false,
    ];

    //配置可自动补扫的部门及需要补充到的状态
    public static $sup = [
        11   =>    1,//折弯部
        13   =>    2,//焊接部
        10   =>    3,//组装部
        6    =>    4,//打磨部
        7    =>    5,//喷涂部
        12   =>    6,//复合部
        8    =>    7,//发货部
    ];

    //联合扫码主次名称
    public static $give_scale_name = [
        1    =>    '主要扫码人',
        2    =>    '协助1',
        3    =>    '协助2',
        4    =>    '协助3',
        5    =>    '协助4',
        6    =>    '协助5',
    ];

    //配置补扫部门ID
    public static $sup_group = 9;

    // 配置产品编号
    public static function giveSn($date=null,$batch=1,$sort=1,$order_id=0){
        if(!$date)$date = time();
        else $date = count($date)==10?$date:strtotime($date);
        $date = date('ymd',$date);

        //如果订单ID存在，则按订单ID+产品序号生成
        if(!empty($order_id))return sprintf ("%04d", $order_id).sprintf ("%03d", $sort);

        return $date.sprintf ("%03d", $batch)."-".sprintf ("%03d", $sort);
    }

    // 配置发货单号
    public static function addressSn($time=0,$sort=null){
        $config = new ConfigModel();

        if(!$time)$time = time();
        //$date = date('ym',$time);
        $date = date('Ymd',$time);
        //if(!$sort)$sort = $config->getConfig('mill_address_sn');

        return $date."-".sprintf ("%04d", $sort);
    }

    //验证部门API操作权限
    public static function role($user=[],$status=null,$give_sort=null){

        $give_sort = explode(',',$give_sort);
        //验证该产品是否已取消生产工艺
        if(empty($give_sort))return '该工程未选择生产工艺';
        if($status>0){
            $key = array_search($status, $give_sort);
            $give_status = '';
            if (!empty($give_sort[$key+1]))$give_status = $give_sort[$key+1];
        }
        $give_status2 = self::$role[$user['group']]['status'][0];

        if($status == $give_status2)return '已出库';
        elseif($status < 0 && abs($status) != $give_status2)return "[".self::$give_status[abs($status)]."]因质检问题，请重新".self::$give_status[abs($status)]."";
        elseif(!in_array($give_status2,$give_sort))return "没有[".self::$give_status[$give_status2]."]工艺";
        elseif(!empty($give_status) && $give_status > $give_status2)return "没有[".self::$give_status[$give_status2]."]权限";
        else return false;

    }
    public static function role_old($user=[],$status=null,$quality_status=null){

        if(is_numeric($quality_status) && $quality_status == 0)$quality_status = true;
        $s = is_numeric($status)?[$status,'status']:[$quality_status,'quality'];
        if(!empty($user) && !empty(self::$role[$user['group']][$s[1]]) && in_array($s[0],self::$role[$user['group']][$s[1]]))return false;

        if(is_numeric($status) && empty(self::$give_status[$status]))return '已出库';

        $note = is_numeric($status)?self::$give_status[$status]:'质检';

        return "无[{$note}]权限";
    }

    //验证部门API是否需要确认流程
    public static function role_sub($user=[],$update=[],$sub=0,$give_status=0){

        $s = [true,'sub'];
        if(!empty($user) && !empty(self::$role[$user['group']][$s[1]]) && in_array($s[0],self::$role[$user['group']][$s[1]])){
            $status = $update['status'];
            $sub ++;
            if($sub == 1){
                if($give_status < 0){
                    $update['status'] --;
                }
                else unset($update['status']);
            }
            elseif ($sub == 2){
                unset($update['status_flow']);
            }
            $update["status{$status}_sub"] = $sub;

        }

        return $update;
    }

    //验证车间不需要的流水线
    public static function roleMill($user=[],$status=null,$is_process=null){

        if(self::roleMillBool($user,$status,$is_process))$status ++;

        return $status;
    }
    //验证车间不需要的流水线
    public static function roleMillBool($user=[],$status=null,$is_process=null){

        return false;
        if($is_process == 0 && $user['group'] == 8)$user['mill_id'] = 0;
        if(!empty($user) && !empty(self::$role_mill[$user['mill_id']]) && in_array($status,self::$role_mill[$user['mill_id']]))return true;

        return false;
    }

    //补一件产品
    public static function repair($id=null,$is_old_id=true){

        $where = ['id'=>$id];
        $give = Db::name('mill_order_archives_give')->where($where)->find();

        $quality_old_id = $give['id'];
        $quality_repair = 1;
        //是否录入补件产品信息
        if(empty($is_old_id)){
            $quality_old_id = '';
            $quality_repair = '';
        }

        //获取最后一件产品的计件数
        $counter = Db::name('mill_order_archives_give')
            ->where(['archives_id'=>$give['archives_id']])
            ->order('counter desc')
            ->value('counter');
        $counter++;//计件数+1
        //获取最后一件产品的序列
        $sort = Db::name('mill_order_archives_give')
            ->where(['give_date'=>$give['give_date'],'batch'=>$give['batch']])
            ->order('sort desc')
            ->value('sort');
        $sort++;//计件数+1
        $add = [
            'quality_old_id'        =>  $quality_old_id,
            'quality_repair'        =>  $quality_repair,
            'order_id'              =>  $give['order_id'],
            'order_pid'             =>  $give['order_pid'],
            'archives_id'           =>  $give['archives_id'],
            'archives_sn'           =>  $give['archives_sn'],
            'counter'               =>  $counter,
            'give_date'             =>  $give['give_date'],
            'batch'                 =>  $give['batch'],
            'sort'                  =>  $sort,
            'give_sn'               =>  self::giveSn($give['give_date'],$give['batch'],$sort,$give['order_id']),
        ];

        Db::name('mill_order_archives_give')->insert($add);
    }


    /**
     * 补足产品的补货状态
     * @param array $user 用户ID
     * @param int $do_status 补充到截止状态
     * @param array $give 产品信息
     * @return mixed
     */
    public static function giveToStatus($user = [],$do_status = 0,$give=[]){
        //$give['give_sort']：当前产品支持哪些扫码环节，根据情况进行补扫
        $give_sort = $give['give_sort'];
        $status = abs($give['status']);
        $log_list = [];//扫码记录
        //补状态
        if ($status < $do_status){
            $give_sort = ",0,{$give_sort},";
            $give_sort = explode(",{$status},",$give_sort);
            $give_sort = explode(',',trim($give_sort[1],','));
            foreach ($give_sort as $v){
                //补确认状态
                if(isset($give["status{$v}_sub"]))$update["status{$v}_sub"] = 2;
                if(isset($give["status{$v}_time"]))$update["status{$v}_time"] = time();

                $update["status_time"] = time();
                $update["status_uid"] = $user['uid'];
                $update["status"] = $do_status;

                //扫码记录
                $log = [
                    'status'            =>  $v,
                    'status_time'       =>  time(),
                    'status_uid'        =>  $user['uid'],
                    'mill_id'           =>  $user['mill_id'],
                    'job_id'            =>  $user['job'],
                    'job_name'          =>  empty($user['job_name'])?'':$user['job_name'],
                    'group_id'          =>  empty($user['group_id'])?$user['group']:$user['group_id'],
                    'give_id'           =>  $give['id'],
                    'give_sn'           =>  $give['give_sn'],
                    'order_id'          =>  $give['order_id'],
                    'order_pid'         =>  $give['order_pid'],
                    'client_id'         =>  $give['client_id'],
                    'archives_id'       =>  $give['archives_id'],
                    'archives_sn'       =>  $give['archives_sn'],
                    'one_area'          =>  $give['one_area'],
                    'counter'           =>  $give['counter'],
                    'model_type'        =>  $give['model_type'],
                    //员工单价设置
                    'give_scale'        =>  $give['give_scale'],
                    'user_price_status' =>  $give['user_price_status'],
                    'user_price_setting'=>  $give['user_price_setting'],
                ];
                if($v != $do_status || empty($user['uid']))$log['is_bu'] = 1;//判断是不是补扫
                if($give['status'] < 0)$log['is_quality'] = 1;//判断是不是质检问题后重做再扫的

                //发货
                if(!empty($give['is_address']) && $v == $do_status){
                    $update["car_id"] = $give['car_id'];
                    $update["address_sn"] = $give['address_sn'];

                    $log['car_id'] = $give['car_id'];
                    $log['address_sn'] = $give['address_sn'];
                    $log['address_date'] = $give['address_date'];
                    $log['address_time'] = $give['address_time'];
                    $log['address_status'] = $give['address_status'];

                }

                $log_list[] = $log;

                if($v == $do_status)break;
            }
        }
        //回滚状态
        elseif ($status > $do_status){

            $give_sort = ",0,{$give_sort},";
            $give_sort = explode(",{$do_status},",$give_sort);
            $give_sort = explode(',',trim($give_sort[1],','));
            foreach ($give_sort as $v){
                //补之前的确认状态
                if(isset($give["status{$v}_sub"]))$update["status{$v}_sub"] = 0;
                if(isset($give["status{$v}_time"]))$update["status{$v}_time"] = 0;

                //如果有过质检，则只更新当前的扫码记录，没有则更新补扫记录
                if($v != $do_status){
                    //获取扫码记录
                    $log = Db::name('mill_order_archives_give_log')->where(['give_id'=>$give['id'],'status'=>$v,'is_last'=>1])->find();
                    if(!empty($log)){
                        $log['is_delete'] = 1;
                        $log_list[$log['id']] = $log;
                    }
                }
            }

            //获取最近一次的扫码记录
            $log = Db::name('mill_order_archives_give_log')->where(['give_id'=>$give['id'],'status'=>$do_status])->find();
            $update["status_time"] = $log['status_time'];
            $update["status_uid"] = $log['status_uid'];
            $update["status"] = $log['status'];

            $update['address_sn'] = '';
            $update['address_date'] = '';
            $update['address_time'] = '';
            $update['address_status'] = '';
            $update['car_id'] = '';
        }
        //质检
        elseif ($give['status'] < 0){
            //补确认状态
            if(isset($give["status{$do_status}_sub"]))$update["status{$do_status}_sub"] = 2;
            $update["status{$do_status}_time"] = time();
            $update["status_time"] = time();
            $update["status_uid"] = $user['uid'];
            $update["status"] = $do_status;

            //扫码记录
            $log = [
                'status'            =>  $do_status,
                'status_time'       =>  time(),
                'status_uid'        =>  $user['uid'],
                'mill_id'           =>  $user['mill_id'],
                'job_id'            =>  $user['job'],
                'job_name'          =>  empty($user['job_name'])?'':$user['job_name'],
                'group_id'          =>  empty($user['group_id'])?$user['group']:$user['group_id'],
                'give_id'           =>  $give['id'],
                'give_sn'           =>  $give['give_sn'],
                'order_id'          =>  $give['order_id'],
                'order_pid'         =>  $give['order_pid'],
                'client_id'         =>  $give['client_id'],
                'archives_id'       =>  $give['archives_id'],
                'archives_sn'       =>  $give['archives_sn'],
                'one_area'          =>  $give['one_area'],
                'counter'           =>  $give['counter'],
                'model_type'        =>  $give['model_type'],
                //员工单价设置
                'give_scale'        =>  $give['give_scale'],
                'user_price_status' =>  $give['user_price_status'],
                'user_price_setting'=>  $give['user_price_setting'],
            ];
            $log['is_quality'] = 1;//判断是不是质检问题后重做再扫的

            $log_list[] = $log;
        }

        $update['log_list'] = $log_list;

        return $update;
    }
    /**
     * 补足产品的补货状态
     * @param array $user 用户ID
     * @param int $do_status 补充到截止状态
     * @param array $give 产品信息
     * @return mixed
     */
    public static function giveToStatus4($user = [],$status_flow = '',$status = 0,$do_status = 8,$give=[]){
        //获取补扫部门的一个账号
        $uid = Db::name('admin_user')->where(['group'=>self::$sup_group,'mill_id'=>$user['mill_id']])->value('id');
        if(empty($uid))$uid = $user['id'];
        $new_status = $status;
        if($status == $do_status){
            $update['status_flow'] = $status_flow;
            $update['status'] = $new_status;
        }
        elseif ($status < $do_status){
            for ($i = $status;$i<$do_status;$i++){

                //补之前的确认状态
                if(isset($give["status{$status}_sub"]))$update["status{$status}_sub"] = 2;

                $status ++;

                if(!strpos($status_flow,"_{$status}|") && !self::roleMillBool($user,$status,$give['is_process'])){
                    $update["status{$status}_time"] = time();
                    if($status_flow)$status_flow .= ",";
                    $status_flow .= "_{$status}|{$uid}_";
                }
                if(!self::roleMillBool($user,$status,$give['is_process']))$new_status = $status;

                //补现在的确认状态
                if(isset($give["status{$status}_sub"]))$update["status{$status}_sub"] = 2;

            }
        }
        elseif ($status > $do_status){
            $new_status_flow = '';
            $new_status = $do_status;
            foreach (explode(',',$status_flow) as $flow){
                $flow_arr = explode('|',trim($flow,'_'));
                if($flow_arr[0] <= $do_status)$new_status_flow .= ",_{$flow_arr[0]}|{$flow_arr[1]}_";
                else {
                    //补之前的确认状态
                    if(isset($give["status{$flow_arr[0]}_sub"]))$update["status{$flow_arr[0]}_sub"] = 1;
                    if(isset($give["status{$flow_arr[0]}_time"]))$update["status{$flow_arr[0]}_time"] = 0;
                }
            }
            $status_flow = trim($new_status_flow,',');

            $update['address_sn'] = '';
            $update['address_date'] = '';
            $update['address_time'] = '';
            $update['address_status'] = '';
            $update['car_id'] = '';
        }

        $update['status_flow'] = $status_flow;
        $update['status'] = $new_status;

        return $update;
    }
    //生成扫码记录
    public static function addGiveLog($log_list = [],$user_arr = [],$quality = []){

        if(!empty($log_list)){
            foreach ($log_list as $log){

                //如果is_delete = 1，则删除相关的扫码记录
                if(!empty($log['is_delete']) && $log['is_delete'] == 1){

                    Db::name('mill_order_archives_give_log')->where(['id'=>$log['id']])->delete();
                    //删除关联的多人联合扫码记录
                    if(!empty($log['scale_log_id']))Db::name('mill_order_archives_give_log')->where(['scale_log_id'=>$log['scale_log_id']])->delete();

                    //直接进入下一个循环
                    continue;
                }
                //如果是补扫，则去掉员工单价
                if(!empty($log['is_bu'])){
                    unset($log['give_scale']);
                    unset($log['user_price_status']);
                    unset($log['user_scale_setting']);
                    unset($log['user_price_setting']);
                    Db::name('mill_order_archives_give_log')->insertGetId($log);
                }
                //如果不是补扫，则分配员工单价
                else{
                    //分配比例
                    $give_scale = $log['give_scale'];
                    //员工单价设置状态
                    //$user_price_status = $log['user_price_status'];
                    //员工单价设置
                    $user_price_setting = json_decode($log['user_price_setting'],true);
                    //根据板型类型，获取对应单价
                    $user_price = 0;
                    if(!empty($user_price_setting[$log['status']]["price"]))$user_price = $user_price_setting[$log['status']]["price"];
                    unset($log['give_scale']);
                    unset($log['user_price_status']);
                    unset($log['user_scale_setting']);
                    //联合扫码人数
                    $scale_count = count($user_arr);
                    //多人联合扫码，按系统分配的比例工作量
                    $mill_give_scale = FinanceModel::orderGiveScale($give_scale,$scale_count);
                    //联合扫码记录ID
                    $scale_log_id = '';
                    foreach ($user_arr as $uk=>$uid){
                        //扫码人
                        $log['status_uid'] = $uid;//扫码人ID
                        //分配比例等级
                        $scale_level = $uk+1;
                        //如果联合扫码员工的人数超过设置人数，则只按设置人数最多的比例进行分配，超过的不分配
                        //if($user_price_status == 2 && isset($mill_give_scale[$scale_level])){
                        if(isset($mill_give_scale[$scale_level])){
                            $log['scale_log_id'] = $scale_log_id;//联合扫码记录ID
                            $log['scale_setting'] = implode(",",$mill_give_scale);//分配比例
                            $log['scale'] = $mill_give_scale[$scale_level];//分配比例
                            $log['scale_level'] = $scale_level;//分配比例等级
                            $log['scale_count'] = $scale_count;//联合扫码人数
                            if($uk == 0)$log['is_main'] = 1;//主体
                            else $log['is_main'] = 0;
                            $log['user_price'] = $user_price;//员工单价
                            $log['price'] = $log['user_price'] * ($log['scale']/100);//实际金额

                            $log_id = Db::name('mill_order_archives_give_log')->insertGetId($log);

                            if($log['is_main'] == 1){
                                $scale_log_id = $log_id;
                                Db::name('mill_order_archives_give_log')->where(['id'=>$log_id])->update(['scale_log_id'=>$scale_log_id]);
                            }
                        }

                    }
                }

                //将当前最新工艺的扫码记录设置为唯一的记录
                $log_where = ['give_id'=>$log['give_id'],'status'=>$log['status']];
                Db::name('mill_order_archives_give_log')->where($log_where)->update(['is_last'=>0]);
                $log_where['is_main'] = 1;
                $last_log_id = Db::name('mill_order_archives_give_log')->where($log_where)->order('status_time desc')->value('id');
                Db::name('mill_order_archives_give_log')->where(['id'=>$last_log_id])->update(['is_last'=>1]);

                //更新质检工位
                self::updateQualityJob($quality,$log);
            }
        }


    }
    //更新质检工位
    //-2:报废 -1:不合格 0:待质检 1:合格 2:已返修
    public static function updateQualityJob($quality=[],$log=[]){

        //更新质检工位
        if(!empty($quality) && empty($quality['log_job_id']) && $quality['status'] == 0){
            $update = [
                'log_job_id'            =>  $log['job_id'],
                'log_job_name'          =>  $log['job_name'],
                'log_time'              =>  time(),
            ];
            Db::name('mill_order_archives_quality_setting')->where(['id'=>$quality['id']])->update($update);
        }

    }
    //质检
    //-2:报废 -1:不合格 0:待质检 1:合格 2:已返修
    public static function quality($user=[],$post=[],$role=true){

        //质检状态 -3:删减的产品 -2:报废 -1:不合格 0:待质检 1:合格 2:已返修
        $quality_status = $post['status'];
        //不合格的流水线 1开平，2开料，3挂件折弯，4组装，5发货
        $give_status = '';
        //责任环节
        if(!empty($post['give_status'])){
            $post['give_status'] = explode(',',$post['give_status']);
            asort($post['give_status']);
            $give_status = reset($post['give_status']);
        }

        $last_status = self::$role[8]['status'][0];

        $where[] = ['g.give_sn','in',$post['give_sn']];
        //$where[] = ['g.status','<',$last_status];
        $list = Db::name('mill_order_archives_give')
            ->alias('g')
            ->field('g.*,a.model,a.page')
            ->leftJoin('mill_order_archives a','a.id=g.archives_id')
            ->where($where)
            ->select();

        if(!empty($list)){
            foreach ($list as $give){
                //产品当前状态
                $status = abs($give['status']);
                //遍历
                //$status_sub = !empty($give_status)?$give_status:$status;

                $save = $log_save = [
                    'quality_uid'           =>  $user['uid'],
                    'quality_status'        =>  $quality_status,
                    'quality_time'          =>  time(),
                    'quality_note'          =>  isset($post['quality_note'])?$post['quality_note']:'',
                    'quality_reason'        =>  isset($post['quality_reason'])?$post['quality_reason']:'',
                ];

                if($quality_status<0){

                    //责任环节
                    $save['quality_flow_status'] = implode(',',$post['give_status']);
                    //责任部门
                    $save['quality_flow_group'] = '';
                    foreach ($post['give_status'] as $gs){
                        $save['quality_flow_group'] .= ",".self::$quality_group[abs($gs)];
                    }
                    $save['quality_flow_group'] = trim($save['quality_flow_group'],',');

                    //重置发货信息
                    $save["car_id"] = '';
                    $save["address_sn"] = '';
                    $save["address_date"] = '';
                    $save["address_time"] = '';
                    $save["address_status"] = 0;

                    //for($i = $status_sub;$i <= $last_status;$i++){
                    //    if(!empty($give["status{$status_sub}_sub"])){
                    //        $save["status{$status_sub}_sub"] = 0;
                    //    }
                    //}

                    $status = -$give_status;
                }
                else {
                    $status = abs($status);
                    //质检合格默认当前生产环节为质检环节
                    if(empty($post['give_status']))$post['give_status'][] = $status;
                }

                $save['status'] = $status;

                if(Db::name('mill_order_archives_give')->where(['id'=>$give['id']])->update($save)){

                    //质检状态 -2:报废 -1:不合格 0:待质检 1:合格 2:已返修
                    //更新质检记录
                    $add = Db::name('mill_order_archives_give')->where(['id'=>$give['id']])->find();

                    $add["give_id"] = $give["id"];
                    unset($add['id']);
                    //质检记录保留发货信息
                    $add["car_id"] = $give["car_id"];
                    $add["address_sn"] = $give["address_sn"];
                    $add["address_date"] = $give["address_date"];
                    $add["address_time"] = $give["address_time"];
                    $add["address_status"] = $give["address_status"];

                    $quality_id = Db::name('mill_order_archives_give_quality')->insertGetId($add);
                    //给每个责任环节的扫码记录记下质检ID
                    foreach ($post['give_status'] as $gs){
                        $log_where = [
                            ['give_id','=',$give['id']],
                            ['status','=',abs($gs)],
                            ['is_main','=',1],
                        ];
                        $log_id = Db::name('mill_order_archives_give_log')->where($log_where)->order('status_time desc')->value('id');

                        $log_save['quality_id'] = $quality_id;
                        Db::name('mill_order_archives_give_log')->where(['id'=>$log_id])->update($log_save);
                    }

                    //检查更新产品主体状态
                    if($status > 0)ArchivesModel::checkStatus($give['archives_id'],$status);
                    //检查更新质检进度
                    if(1 == 1){
                        //根据板型、图号、工艺。获取质检设置
                        $setting_where = $setting_where_next = [
                            'l.order_id'      =>  $give['order_id'],
                            'l.model'         =>  $give['model'],
                            'l.give_status'   =>  abs($status),
                            'l.status'        =>  0,
                        ];
                        $setting_where_2 = "FIND_IN_SET('{$give['page']}',l.page)";
                        $setting = Db::name('mill_order_archives_quality_setting')->alias('l')->where($setting_where)->where($setting_where_2)->find();
                        //质检设置存在，则更新质检进度
                        if(!empty($setting)){
                            //根据板型、图号。获取已质检的数量
                            unset($setting_where['l.give_status']);
                            unset($setting_where['l.model']);
                            $setting_where['l.status'] = $status;
                            $setting_where['a.page'] = $give['page'];
                            $setting_where['a.model'] = $give['model'];
                            $log_quality_number = Db::name('mill_order_archives_give_log')
                                ->alias('l')
                                ->leftJoin('mill_order_archives a','a.id=l.archives_id')
                                ->where($setting_where)
                                ->where("l.quality_status <> 0")
                                ->count();

                            $setting_save = [
                                'log_quality_number'        =>  $log_quality_number,
                                'quality_time'              =>  time(),
                            ];

                            if($log_quality_number >= $setting['number']){
                                $setting_save['log_quality_number'] = $setting['number'];
                                $setting_save['status'] = 1;
                                $setting_save['log_job_id'] = '';
                                $setting_save['log_job_name'] = '';

                            }
                            Db::name('mill_order_archives_quality_setting')->where(['id'=>$setting['id']])->update($setting_save);

                        }

                    }
                }
            }

            return true;

        }
        return false;

    }

    //根据用户ID或扫码状态获取对应值
    static function giveStatusOrUid($status_flow=null,$uid=null,$status=null){
        $data = '';
        if($uid){
            $give_status = explode("|{$uid}_",$status_flow);
            $give_status = array_filter($give_status);

            if(substr_count($status_flow,"|{$uid}_") == 1)$give_status = $give_status[0];
            else $give_status = end($give_status);

            if(isset($give_status)){
                $give_status = explode(',_',$give_status);
                $data = trim(end($give_status),'_');
            }

        }
        elseif ($status){
            $uid = explode("_{$status}|",$status_flow);
            if(isset($uid[1])){
                $uid = $uid[1];
                $uid = explode(',_',$uid);
                $data = trim($uid[0],'_');
            }
        }

        return $data;
    }

    // 分配发货单号
    public static function getAddressSn($time = 0){

        $config = new ConfigModel();

        //默认今天时间
        if(empty($time))$time = time();
        $update_time = true;
        //如果不是今天时间，则根据历史发货单号分配
        if(date('Ymd',$time) != date('Ymd'))$update_time = false;

        //分配今天的发货单
        if($update_time) {
            $sort = $config->getConfig('mill_address_sn');
            //发货单号计数器，如果不是今天的计数器，则重置并更新计数器
            if (strpos($sort, date('Ymd')) === false)ConfigModel::where('name', 'mill_address_sn')->update(['value' => date('Ymd') . "-0"]);
            $sort = $config->getConfig('mill_address_sn');
        }
        //分配历史发货单
        else {
            $status = self::$role[8]['status'][0];
            $where = [
                ["status{$status}_time",'between time',[date('Y-m-d',$time),date('Y-m-d 23:59:59',$time)]]
            ];
            $sort = Db::name('mill_order_archives_give')->where($where)->order('address_sn desc')->value('DISTINCT address_sn');
            if(empty($sort))$sort =  date('Ymd',$time) . "-0";
        }
        $sort = explode('-', $sort)[1];
        $sort ++;

        //分配发货单号
        $address_sn = self::addressSn($time,$sort);
        //更新发货单号
        if($update_time)ConfigModel::where('name', 'mill_address_sn')->update(['value' =>date('Ymd')."-".($sort)]);

        return $address_sn;
    }

    // 分配开平单号
    public static function getCuttingLogSn($time = 0){

        $config = new ConfigModel();

        //默认今天时间
        if(empty($time))$time = time();
        $update_time = true;
        //如果不是今天时间，则根据历史开平单号分配
        if(date('Ymd',$time) != date('Ymd'))$update_time = false;

        //分配今天的开平单号
        if($update_time) {
            $sort = $config->getConfig('mill_cutting_log_sn');
            //开平单号计数器，如果不是今天的计数器，则重置并更新计数器
            if (strpos($sort, date('Ymd')) === false)ConfigModel::where('name', 'mill_cutting_log_sn')->update(['value' => date('Ymd') . "-0"]);
            $sort = $config->getConfig('mill_cutting_log_sn');
        }
        //分配历史开平单号
        else {
            $where = [
                ["cutting_log_time",'between time',[date('Y-m-d',$time),date('Y-m-d 23:59:59',$time)]]
            ];
            $sort = Db::name('mill_order_archives_cutting')->where($where)->order('mill_cutting_log_sn desc')->value('DISTINCT mill_cutting_log_sn');
            if(empty($sort))$sort =  date('Ymd',$time) . "-0";
        }
        $sort = explode('-', $sort);
        $sort = end($sort);
        $sort ++;

        //更新开平单号
        if($update_time)ConfigModel::where('name', 'mill_cutting_log_sn')->update(['value' =>date('Ymd')."-".($sort)]);

        return "JPKP-".date('Ymd',$time)."-".$sort;
    }

    //定时任务，超过24小时未确认发货，则自动发货
    static function taskSubGiveAddress($address_sn='',$address_time=''){

        //24小时
        $time = (time()-86400);
        //发货状态
        $status = self::$role[8]['status'][0];
        //按批次分组
        $where = [
            ['address_sn','<>',''],
            ['status','=',$status],
            ['address_status','=',0],
        ];
        if(empty($address_sn)){
            $where[] = ["status{$status}_time",'>',0];
            $where[] = ["status{$status}_time",'<=',$time];
        }
        else $where[] = ['address_sn','=',$address_sn];

        $archives_ids = '';
        $give_list = Db::name('mill_order_archives_give')
            //->field("address_sn,order_pid,archives_sn,status{$status}_time,GROUP_CONCAT(id) as give_ids,GROUP_CONCAT(DISTINCT archives_id) as archives_ids")
            ->field("address_sn,order_id,order_pid,archives_sn,status{$status}_time")
            ->where($where)
            ->group('address_sn,order_id')
            ->select();
        $address_sn_s = Db::name('mill_order_archives_give')->where($where)->column('address_sn');
        if(!empty($address_sn_s))$address_sn_s = implode(',',$address_sn_s);

        if(!empty($give_list)){

            foreach ($give_list as $v){

                $time = strtotime(date('Y-m-d 23:59:59',$v["status{$status}_time"]));
                if(!empty($address_time))$time = $address_time;

                //$archives_ids .= ",{$v['archives_ids']}";
                //分配发货单号
                if(strpos($address_sn_s,$v['address_sn']) !== false){
                    $address_sn = $v['address_sn'];
                    $address_sn_s = str_replace($v['address_sn'],"",$address_sn_s);
                }
                else $address_sn = self::getAddressSn($time);

                $save = [
                    'address_status'        =>  1,
                    'address_date'          =>  date('Y-m-d',$time),
                    'address_time'          =>  $time,
                    'address_sn'            =>  $address_sn,
                ];

                //$give_where = [['id','in',$v['give_ids']]];
                $give_where = [['address_sn','=',$v['address_sn']],['order_id','=',$v['order_id']]];
                $up_log = Db::name('mill_order_archives_give')->where($give_where)->update($save);

                //$give_log_where = [['give_id','in',$v['give_ids']],['status','=',$status]];
                $give_log_where = [['address_sn','=',$v['address_sn']],['order_id','=',$v['order_id']]];
                $up_log2 = Db::name('mill_order_archives_give_log')->where($give_log_where)->update($save);

            }
            //exit;

            ////检查更新产品主体状态
            //if(!empty($archives_ids)){
            //    $archives_ids = explode(',',trim($archives_ids,','));
            //    foreach ($archives_ids as $archives_id){
            //        ArchivesModel::checkStatus($archives_id,$status);
            //    }
            //}

        }
    }

}
